package com.edu.hre.struts.action.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreProject;
import com.edu.hre.db.pojo.HreProjectAdmin;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.LocationUpdateForm;
import com.edu.hre.struts.form.admin.ProjectUpdateForm;

public class ProjectUpdateAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(ProjectUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "projectUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		ProjectUpdateForm beanForm = (ProjectUpdateForm) form;
		beanForm.setIsAddNew(true); 

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Save or update.
		HreProject tmp = new HreProject();
		tmp.setCustomerId(beanForm.getCustomerId());
		tmp.setName(CommonUtils.normalizeString(beanForm.getName()));
		tmp.setDescription(CommonUtils.normalizeString(beanForm.getDescription()));
		tmp.setIsDeleted(false);
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		HreProjectAdmin[] proAds = new HreProjectAdmin[5];
		for (int ind = 0; ind < 5; ind++) {
			proAds[ind] = new HreProjectAdmin();
			proAds[ind].setProjectId(tmp.getProjectId());
		}

		proAds[0].setEmpNumber(beanForm.getAdmin1EmpNumber());
		proAds[1].setEmpNumber(beanForm.getAdmin2EmpNumber());
		proAds[2].setEmpNumber(beanForm.getAdmin3EmpNumber());
		proAds[3].setEmpNumber(beanForm.getAdmin4EmpNumber());
		proAds[4].setEmpNumber(beanForm.getAdmin5EmpNumber());
		
		for (int ind = 0; ind < 5; ind++) {
			if (proAds[ind].getEmpNumber() > 0) {
				baseService.saveOrUpdate(proAds[ind]);
			}
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		ProjectUpdateForm beanForm = (ProjectUpdateForm) form;
		beanForm.setIsAddNew(false); 
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreProject tmp = baseService.getFirstPojo("projectId", Compare.EQUAL, id, null, null, 0, HreProject.class);
			
			if (tmp == null) {
				initFormBean(beanForm);
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setProjectId(tmp.getProjectId());
			beanForm.setCustomerId(tmp.getCustomerId());
			beanForm.setName(CommonUtils.normalizeString(tmp.getName()));
			beanForm.setDescription(CommonUtils.normalizeString(tmp.getDescription()));
			beanForm.setDeleted(tmp.getIsDeleted());

			// Get ID for all administrators.
			List<HreProjectAdmin> proAds = baseService.getPojos("projectId", Compare.EQUAL, tmp.getProjectId(), new String[]{"id"}, null, -1, 0, HreProjectAdmin.class);
			if (proAds.size() >= 1) {
				beanForm.setAdmin1EmpNumber(proAds.get(0).getEmpNumber());
			}
			if (proAds.size() >= 2) {
				beanForm.setAdmin2EmpNumber(proAds.get(1).getEmpNumber());
			}
			if (proAds.size() >= 3) {
				beanForm.setAdmin3EmpNumber(proAds.get(2).getEmpNumber());
			}
			if (proAds.size() >= 4) {
				beanForm.setAdmin4EmpNumber(proAds.get(3).getEmpNumber());
			}
			if (proAds.size() >= 5) {
				beanForm.setAdmin5EmpNumber(proAds.get(4).getEmpNumber());
			}

			initFormBean(beanForm);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Save or update.
		HreProject tmp = baseService.getFirstPojo("projectId", Compare.EQUAL, beanForm.getProjectId(), null, null, 0, HreProject.class);
		if (tmp == null) {
			initFormBean(beanForm);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}

		tmp.setProjectId(beanForm.getProjectId());
		tmp.setCustomerId(beanForm.getCustomerId());
		tmp.setName(CommonUtils.normalizeString(beanForm.getName()));
		tmp.setDescription(CommonUtils.normalizeString(beanForm.getDescription()));
		tmp.setIsDeleted(false);
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		List<HreProjectAdmin> proAds = baseService.getPojos("projectId", Compare.EQUAL, tmp.getProjectId(), new String[]{"id"}, null, -1, 0, HreProjectAdmin.class);
		
		List<Integer> newAdNumbers = new ArrayList<Integer>();
		if (beanForm.getAdmin1EmpNumber() > 0) {
			newAdNumbers.add(beanForm.getAdmin1EmpNumber());
		}
		if (beanForm.getAdmin2EmpNumber() > 0) {
			newAdNumbers.add(beanForm.getAdmin2EmpNumber());
		}
		if (beanForm.getAdmin3EmpNumber() > 0) {
			newAdNumbers.add(beanForm.getAdmin3EmpNumber());
		}
		if (beanForm.getAdmin4EmpNumber() > 0) {
			newAdNumbers.add(beanForm.getAdmin4EmpNumber());
		}
		if (beanForm.getAdmin5EmpNumber() > 0) {
			newAdNumbers.add(beanForm.getAdmin5EmpNumber());
		}
		
		for (int ind = 0; ind < newAdNumbers.size(); ind++) {
			if (ind < proAds.size()) {
				proAds.get(ind).setProjectId(tmp.getProjectId());
				proAds.get(ind).setEmpNumber(newAdNumbers.get(ind));
			} else {
				HreProjectAdmin ad = new HreProjectAdmin();
				ad.setProjectId(tmp.getProjectId());
				ad.setEmpNumber(newAdNumbers.get(ind));
				proAds.add(ad);
			}
		}
		
		for (int ind = newAdNumbers.size(); ind < proAds.size(); ind++) {
			baseService.deletePojo(proAds.get(ind));
		}

		for (int ind = 0; ind < proAds.size(); ind++) {
			if (proAds.get(ind).getEmpNumber() > 0) {
				baseService.saveOrUpdate(proAds.get(ind));
			}
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	private void initFormBean(ProjectUpdateForm beanForm) {

		beanForm.setAllCustomers(ComboBoxInit.getAllCustomers(false));
		beanForm.setAllEmployees(ComboBoxInit.getAllEmployees(true));
	}
	
	private String validateForm (ProjectUpdateForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getName()))){
			return "Project name cannot be blank!";
		}
		
		// Check if two administrators are same.
		if ((beanForm.getAdmin1EmpNumber() == beanForm.getAdmin2EmpNumber() && beanForm.getAdmin1EmpNumber() != 0)
				|| (beanForm.getAdmin1EmpNumber() == beanForm.getAdmin3EmpNumber() && beanForm.getAdmin1EmpNumber() != 0)
				|| (beanForm.getAdmin1EmpNumber() == beanForm.getAdmin4EmpNumber() && beanForm.getAdmin1EmpNumber() != 0)
				|| (beanForm.getAdmin1EmpNumber() == beanForm.getAdmin5EmpNumber() && beanForm.getAdmin1EmpNumber() != 0)
				|| (beanForm.getAdmin2EmpNumber() == beanForm.getAdmin3EmpNumber() && beanForm.getAdmin2EmpNumber() != 0)
				|| (beanForm.getAdmin2EmpNumber() == beanForm.getAdmin4EmpNumber() && beanForm.getAdmin2EmpNumber() != 0)
				|| (beanForm.getAdmin2EmpNumber() == beanForm.getAdmin5EmpNumber() && beanForm.getAdmin2EmpNumber() != 0)
				|| (beanForm.getAdmin3EmpNumber() == beanForm.getAdmin4EmpNumber() && beanForm.getAdmin3EmpNumber() != 0)
				|| (beanForm.getAdmin3EmpNumber() == beanForm.getAdmin5EmpNumber() && beanForm.getAdmin3EmpNumber() != 0)
				|| (beanForm.getAdmin4EmpNumber() == beanForm.getAdmin5EmpNumber() && beanForm.getAdmin4EmpNumber() != 0)) {
			
			return "Two of the administrators are same!";
		}

		return StringConstants.BLANK;
	}
}